package com.hsogoo.avatar.transport;

import com.google.common.collect.Maps;
import com.hsogoo.avatar.model.AvatarAddress;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @Author huangsaigang
 * Created @2018/9/29.
 */
@Slf4j
public class AvatarConnectionManager {

    private final ConcurrentMap<AvatarAddress, CopyOnWriteArrayList<AvatarConnection>> connections = Maps.newConcurrentMap();

    /**
     * 设置为由avatar自动管理连接
     */
    public void manage(AvatarConnection connection) {
        AvatarAddress address = connection.address();
        CopyOnWriteArrayList<AvatarConnection> list = connections.get(address);
        if (list == null) {
            CopyOnWriteArrayList<AvatarConnection> newList = new CopyOnWriteArrayList<>();
            list = connections.putIfAbsent(address, newList);
            if (list == null) {
                list = newList;
            }
        }
        list.add(connection);
    }

    /**
     * 取消对所有地址的自动重连
     */
    public void cancelAllAutoReconnect() {
        for (AvatarAddress address : connections.keySet()) {
            cancelAutoReconnect(address);
        }
    }

    /**
     * 取消对指定地址的自动重连
     */
    public void cancelAutoReconnect(AvatarAddress address) {
        CopyOnWriteArrayList<AvatarConnection> list = connections.remove(address);
        if (list != null) {
            for (AvatarConnection c : list) {
                c.setReconnect(false);
            }
            log.warn("Cancel reconnect to: {}.", address);
        }
    }
}
